<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="text-center">
        <h1 class="text-3xl text-[#303133]">育考星考试平台</h1>
      </div>

      <!-- 角色选择 -->
      <el-radio-group
        v-model="role"
        class="mt-8 flex justify-center"
        size="large"
      >
        <el-radio-button value="student" class="mr-8">学生</el-radio-button>
        <el-radio-button value="teacher">教师</el-radio-button>
      </el-radio-group>

      <!-- 登录表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        class="mt-8"
        size="large"
        @keyup.enter="handleLogin(formRef)"
      >
        <el-form-item prop="username">
          <el-input
            v-model="formData.username"
            :placeholder="
              role === 'student' ? '请输入学号或邮箱' : '请输入工号或邮箱'
            "
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 新增验证码表单项 -->
        <el-form-item prop="captcha">
          <div class="flex items-center space-x-4">
            <el-input
              v-model="formData.captcha"
              placeholder="请输入验证码"
              class="flex-1"
            >
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <!-- 验证码图片区域 -->
            <div
              class="h-[42px] w-[120px] flex items-center justify-center bg-[#f5f7fa] rounded-xl cursor-pointer"
              @click="refreshCaptcha"
            >
              <el-image
                v-if="captchaUrl"
                :src="captchaUrl"
                fit="contain"
                class="h-full"
              />
              <el-icon v-else class="text-[#909399]"><Refresh /></el-icon>
            </div>
          </div>
        </el-form-item>

        <el-button
          type="primary"
          class="w-full"
          size="large"
          :loading="loading"
          @click="handleLogin(formRef)"
        >
          登录
        </el-button>
      </el-form>
      <div class="mt-4 text-center">
        <span class="text-center text-sm text-[#909399]"
          >&copy;POWER BY BLYS</span
        >
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { User, Lock, Key, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
  getCaptcha,
  verifyCode,
  getStudentRoute,
  getTeacherRoute,
} from '@/api/user'
import { Encrypt } from '@/utils/secret'
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'
import { handleRouteComponent } from '@/utils/index'

const router = useRouter()
const formRef = ref(null)
const role = ref('student')
const loading = ref(false)

// 验证码图片
const captchaUrl = ref('')

const userStore = useUserStore()

// 获取验证码
const getcaptcha = async () => {
  try {
    const res = await getCaptcha()
    const blob = new Blob([res], { type: 'image/png' })
    if (captchaUrl.value) {
      URL.revokeObjectURL(captchaUrl.value) // 释放旧的 URL
    }
    captchaUrl.value = URL.createObjectURL(blob)
  } catch (error) {
    console.error('获取验证码错误:', error)
    // ElMessage.error('获取验证码失败')
  }
}

const formData = reactive({
  username: '',
  password: '',
  remember: false,
  captcha: '',
  captchaUrl: '',
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
}

/**
 * 处理登录表单提交
 */
const handleLogin = async (formEl) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 验证码验证
        const verifyRes = await verifyCode(formData.captcha)
        if (verifyRes.code === 1) {
          // 密码加密
          const encryptedPassword = Encrypt(formData.password)

          // 设置当前选择的角色
          const currentRole = role.value
          localStorage.setItem('role', currentRole)

          // 使用 store 进行登录
          const result = await userStore.login({
            username: formData.username,
            password: encryptedPassword,
            loginType: currentRole === 'student' ? 1 : 2,
          })

          if (result.success) {
            try {
              ElMessage.success('登录成功')
              // 获取用户信息
              userStore.getUserinfo()
              // 设置role
              userStore.setRole(currentRole)
              // 直接跳转即可
              const targetPath = `/${currentRole}`
              router.push(targetPath)
            } catch (infoError) {
              console.error('获取用户信息失败:', infoError)
              userStore.resetState()
            }
          }
        } else {
          ElMessage.error('验证码错误')
          refreshCaptcha()
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error?.message || '登录失败，请重试')
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    }
  })
}

// 刷新验证码
const refreshCaptcha = async () => {
  formData.captcha = '' // 清空验证码输入
  await getcaptcha() // 重新获取验证码
}

onMounted(() => {
  // 获取验证码
  getcaptcha()
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (captchaUrl.value) {
    URL.revokeObjectURL(captchaUrl.value)
  }
})
</script>

<style lang="less" scoped>
.login-container {
  display: flex;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to bottom, #ecf5ff, white);

  .login-card {
    width: 100%;
    max-width: 28rem; // 相当于 max-w-md
    overflow: visible;
    border-radius: 24px;
    box-shadow: 0 20px 60px -15px rgba(0, 0, 0, 0.1);

    :deep(.el-card__body) {
      padding: 2.5rem;
    }
  }

  :deep(.el-input) {
    .el-input__wrapper {
      border-radius: 0.75rem;
      background-color: #f5f7fa;
      padding: 1px 15px;
    }

    .el-input__inner {
      height: 42px;
    }
  }

  :deep(.el-radio-group) {
    .el-radio-button__inner {
      border-radius: 9999px;
    }

    .el-radio-button:first-child .el-radio-button__inner,
    .el-radio-button:last-child .el-radio-button__inner {
      border-radius: 9999px;
    }
  }

  :deep(.el-button) {
    border-radius: 0.75rem;
    height: 46px;
  }
}

// 其他通用样式
.text-center {
  text-align: center;
}

.mt-8 {
  margin-top: 2rem;
}

.mt-4 {
  margin-top: 1rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.w-full {
  width: 100%;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-center {
  justify-content: center;
}

.justify-between {
  justify-content: space-between;
}

.text-3xl {
  font-size: 1.875rem;
  line-height: 2.25rem;
}

.font-light {
  font-weight: 300;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}
</style>
